package com.example.leoss.zhuye.File_xianshi;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.icu.text.DecimalFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.leoss.R;
import com.example.leoss.zhuye.ShouyeFragment;
import com.example.leoss.duanxingxufa.MsgMobanActivity;
import com.example.leoss.duanxingxufa.SQliteMsg.Caozuo2;
import com.example.leoss.duanxingxufa.SQliteMsg.Msg;
import com.example.leoss.duanxingxufa.SendActivity;
import com.example.leoss.zhuye.ParseXls.Caozuo_teacher;
import com.example.leoss.zhuye.ParseXls.Teacher_info;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ToFile_duanxinactivity extends AppCompatActivity implements SearchView.OnQueryTextListener {

    private Context mContext;
    private List<FileBean> fileBeans =new ArrayList<>();
    private AnimalAdapter mAdapter = null;
    private ListView list_animal;
    private SearchView id_file_search1s;
    private static final int EVENT_TIME_TO_CHANGE_IMAGE = 100;
    private static ProgressDialog dialog;
    String docId = null;
    int data = 0;
    public String path;
    ProgressDialog progressDialog;
    ShouyeFragment shouyeFragment;
    EditText id_file_ed_model1s;
    boolean dakeiwenjian = false;
    private String[] stringRow;
    private  String[] count;
    private String smsModel2;
    public  int panduan=1;
    private String content;
    private  static   String Stumovename ,Stumovephone;
    private String smsModel23;
    private SharedPreferences sp;
    private static String EX;
    int Phne = -1,Name=-1;
    int p=0;
    int n=0;
    String sms="";
    private String smsMode;
    private  List listDir1=new ArrayList();
    private  List listDir2=new ArrayList();
    private  List listDir3=new ArrayList();
    ExecutorService executorService;
    private int biaoji=1;

    public static void closeProgressDialog() {
        dialog.dismiss();
    }

    //开始
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_to_file_duanxinqunfa);
        setTitle("选择Excel表格");

        shouyeFragment = new ShouyeFragment();
        getFilesByType(0);

        Intent intent = getIntent();
        smsModel2 = intent.getStringExtra("smsModel");
        smsMode = intent.getStringExtra("smsModel");
        data = intent.getIntExtra("data", 0);

        id_file_search1s = (SearchView) findViewById(R.id.id_file_search2);//搜索控件
        id_file_search1s.setOnQueryTextListener(this);

        mContext = this;
        list_animal = (ListView) findViewById(R.id.list_view2);



/**
 *  listview事件
 */
        list_animal.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, final View view, int i, long l) {

                TextView id_name = view.findViewById(R.id.id_name);
                path = id_name.getText().toString();


                AlertDialog.Builder normalMoreButtonDialog = new AlertDialog.Builder(ToFile_duanxinactivity.this);
                normalMoreButtonDialog.setTitle("数据解析");
                normalMoreButtonDialog.setMessage("确定解析\t" + getFileName(path) + "\t此文件吗?");
                //设置按钮
                normalMoreButtonDialog.setPositiveButton("确定"
                        , new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                dialog.dismiss();
                                showSpinner();

                            }
                        });

                normalMoreButtonDialog.setNeutralButton("取消"
                        , new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                normalMoreButtonDialog.create().show();
            }

        });


        list_animal.setTextFilterEnabled(true);
        id_file_search1s.setIconifiedByDefault(false);
        id_file_search1s.setOnQueryTextListener(this);
//        id_file_search1s.setSubmitButtonEnabled(true);
        id_file_search1s.setSubmitButtonEnabled(false);

    }

    /**
     * 文件名替换
     *
     * @param pathandname
     * @return
     */
    public String getFileName(String pathandname) {

        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        } else {
            return null;
        }

    }

    /**
     * 菜单
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.tofile_excel, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.open_file1:
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("text/plain");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 200);
                break;
            case R.id.meun_xiayibu:
                startActivity(new Intent(ToFile_duanxinactivity.this,SendActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 错误提示
     */
    public boolean Apledialog(final String title, final String messge, final boolean boole)
    {
        boolean cheggong = boole;


        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                AlertDialog.Builder normalMoreButtonDialog = new AlertDialog.Builder(ToFile_duanxinactivity.this);
                normalMoreButtonDialog.setTitle(title);
                normalMoreButtonDialog.setMessage(messge);
                //设置按钮
                normalMoreButtonDialog.setNegativeButton("确定"
                        , new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {


                                dialog.dismiss();
                                if (boole==true)
                                {
                                    startActivity(new Intent(ToFile_duanxinactivity.this,SendActivity.class));
                                }

                            }
                        });

                normalMoreButtonDialog.create().show();
            }
        });
        return boole;
    }

    /**
     * @throws FileNotFoundException
     */
    public void onReadClick(String path) throws FileNotFoundException
    {
        panduan=1;
        try {
            InputStream input = new FileInputStream(path); // 将文件读取成流
            if (path.endsWith(".xls")) {
                HSSFWorkbook workbook_t;
                HSSFSheet sheet_t;
                workbook_t = new HSSFWorkbook(input);
                sheet_t = workbook_t.getSheetAt(0);
                sheetAtchatXLS(workbook_t, sheet_t);
            } else if (path.endsWith(".xlsx")) {
                XSSFWorkbook workbook1 = new XSSFWorkbook(input);
                XSSFSheet sheet1 = workbook1.getSheetAt(0);
                sheetAtchatXLSX(workbook1, sheet1);
            } else {
                Apledialog("文件出错", "请确定的是选择xls或者xlsx文件!", false); panduan=0;
            }

        } catch (Exception e) {
            Apledialog("文件出错", "文件错误，换一个文件试试!", false);
            panduan=0;
        }

    }

    //xlsx
    private void sheetAtchatXLSX(XSSFWorkbook workbook1, XSSFSheet sheet1) {
        //通讯录录入
        try {
            int rowsCount = sheet1.getPhysicalNumberOfRows();

            FormulaEvaluator formulaEvaluator = workbook1.getCreationHelper().createFormulaEvaluator();

            Log.e("rowsCount","-----------------------------------------------"+rowsCount);//行数0到n-1


            for (int r = 0; r < rowsCount; r++) {

                Row row = sheet1.getRow(r);

                int cellsCount = row.getPhysicalNumberOfCells();//获取不为空的列个数。.getLastCellNum()

                Log.e("cellsCount","-----------------------------------------------"+cellsCount);//列数0到n-1
//               int cellsCount = row.getLastCellNum();

                stringRow = new String[cellsCount];
                count=new String[cellsCount];

                for (int c = 0; c < cellsCount; c++)
                {

                    if (r == 0) {
                        if (c>=2) {

                            count[c] = getCellAsString(row, c, formulaEvaluator);//第一行的数据
                            sms=sms.concat("\n"+"{coun"+c+"} "+"{num"+c+"}");
                            sms=sms.replace("{coun"+c+"}",count[c]); //替换

                            Log.e("<<<<<<<<<<","sms="+sms) ;

                        }
                        if (c == cellsCount - 1){
                            smsModel2=smsModel2+sms;

                            //存一行模板
//                            sp=getSharedPreferences("ExcelADD",MODE_PRIVATE);
//                            SharedPreferences.Editor editor=sp.edit();
//                            editor.putString("EX",smsModel2);
//                            editor.apply();
                            EX=smsModel2;

                        }
                    }


                    if (r>=1&&c>=2){
                        stringRow[c] = getCellAsString(row, c, formulaEvaluator);
                        smsModel2=smsModel2.replace("{num"+c+"}",stringRow[c]);

                    }
                    if (c==0){
                        stringRow[c] = getCellAsString(row, c, formulaEvaluator);
                    }
                    if (c==1){
                        stringRow[c] = getCellAsString(row, c, formulaEvaluator);
                    }


                }

                if (r>=1){

                    smsModel2=smsModel2.replace("{name}",stringRow[0]);
                    Log.e("","content****************//////////////////////////////////////////////////---------------------"+smsModel2);

                    Msg  msg = new Msg(stringRow[0], stringRow[1], smsModel2);
                    Caozuo2 caozuo1 = new Caozuo2(this);
                    caozuo1.tianjia(msg);
                }



                //smsModel2=sp.getString("EX","");

                smsModel2=EX;


            }


        } catch (Exception e) {
            Apledialog("", "不好意思...\n解析出错了" + e.toString(), false); panduan=0;
        }

        Log.e("",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>sms="+smsModel2) ;

        if (panduan!=0){ Apledialog("", "数据添加成功", true);}

//        SharedPreferences.Editor editor=sp.edit();
//        editor.putString("EX","");
//        editor.clear();
//        editor.commit();
    }


    //xls
    private void sheetAtchatXLS(HSSFWorkbook workbook, HSSFSheet sheet) {

        try {
            int rowsCount = sheet.getPhysicalNumberOfRows();//获取行数n

            Log.e("rowsCount","-----------------------------------------------"+rowsCount);//行数0到n-1

            FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();

            for (int r = 0; r < rowsCount; r++)
            {

                Row row = sheet.getRow(r);

                int cellsCount = row.getPhysicalNumberOfCells();//获取不为空的列个数。.getLastCellNum()
                Log.e("cellsCount","-----------------------------------------------"+cellsCount);//列数0到n-1
//               int cellsCount = row.getLastCellNum();
                stringRow = new String[cellsCount];
                count=new String[cellsCount];

                for (int c = 0; c < cellsCount; c++) {

                    if (r == 0) {

                        if (c>=2) {

                            count[c] = getCellAsString(row, c, formulaEvaluator);//第一行的数据
                            sms=sms.concat("\n"+"{coun"+c+"}:"+"{num"+c+"}");
                             sms=sms.replace("{coun"+c+"}",count[c]); //替换

                             Log.e("<<<<<<<<<<","sms="+sms) ;

                        }

                        if (c == cellsCount - 1){
                            smsModel2=smsModel2+sms;

                            //存一行模板
//                            sp=getSharedPreferences("ExcelADD",MODE_PRIVATE);
//                            SharedPreferences.Editor editor=sp.edit();
//                            editor.putString("EX",smsModel2);
//                            editor.apply();
                            EX=smsModel2;

                        }

                    }


                    if (r>=1&&c>=2){
                        stringRow[c] = getCellAsString(row, c, formulaEvaluator);
                        smsModel2=smsModel2.replace("{num"+c+"}",stringRow[c]);

                    }

                    if (c==0){
                        stringRow[c] = getCellAsString(row, c, formulaEvaluator);
                    }
                    if (c==1){
                        stringRow[c] = getCellAsString(row, c, formulaEvaluator);
                    }


                }

                  if (r>=1){

                      smsModel2=smsModel2.replace("{name}",stringRow[0]);
                      Log.e("","content****************//////////////////////////////////////////////////---------------------"+smsModel2);

                      Msg  msg = new Msg(stringRow[0], stringRow[1], smsModel2);
                      Caozuo2 caozuo1 = new Caozuo2(this);
                      caozuo1.tianjia(msg);
                  }



                //smsModel2=sp.getString("EX","");

                smsModel2=EX;


            }


        } catch (Exception e) {
            Apledialog("", "不好意思...\n解析出错了" + e.toString(), false); panduan=0;
        }

        Log.e("",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>sms="+smsModel2) ;

        if (panduan!=0){ Apledialog("", "数据添加成功", true);}

//        SharedPreferences.Editor editor=sp.edit();
//        editor.putString("EX","");
//        editor.clear();
//        editor.commit();
    }

    @Override
    protected void onStop() {
        super.onStop();
        sms = "";
        smsModel2 = smsMode;
    }

    /**
     * 列名判断 找到电话号码列和姓名列
     */
    private int counName(int c) {
        int counName=-1;

        Log.e("","----------------------------------------------counName()");
        for (int i=0;i<=c;i++)
        {
           if (count[i].equals("name")){
               Stumovename="name";
            counName=i;break;

        }else
        if (count[i].equals("姓名")){
            Stumovename="姓名";
            counName=i;break;
        }

        }

        return counName;
    }

    /**
     * 列名判断 找到电话号码
     */
    private int counPhne(int c){
        int counPhne=-1;
              Log.e("","----------------------------------------------counPhne()");
        for (int i=0;i<=c;i++){

            if (count[i].equals("Phone")){
                Stumovephone="Phone";
             counPhne=i;break;
            }
            else if (count[i].equals("PhoneNumber")){
                Stumovephone="PhoneNumber";
                counPhne=i;break;
            } if (count[i].equals("phone")){
                Stumovephone="phone";
                counPhne=i;break;
            }
            else if (count[i].equals("phonenumber")){
                Stumovephone="phonenumber";
                counPhne=i;break;
            }
              else if (count[i].equals("电话号码")){
                Stumovephone="电话号码";
                counPhne=i;break;
            }
           else if (count[i].contains("电话")){
                Stumovephone="电话";
                counPhne=i;break;
            }

        }
        return counPhne;
    }


    public void showSpinner() {
        progressDialog = ProgressDialog.show(ToFile_duanxinactivity.this, "信息", "正在解析请耐心等待", true, true);
        //调用静态方法显示进度条
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    onReadClick(path);

                } catch (Exception e) {
                    Apledialog("", "文件地址出错了", false); panduan=0;
                }
                Message message = new Message();
                message.what = 0;
                handler.sendMessage(message);
                // handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
            }

        }).start();
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
            progressDialog.dismiss();// 关闭ProgressDialog
        }
    };


    /**
     * 单元格类型判断
     * @param formulaEvaluator
     * @return
     */
    protected String getCellAsString(Row row, int c, FormulaEvaluator formulaEvaluator) {
        String value = "";
        Cell cell = row.getCell(c);
        CellValue cellValue = formulaEvaluator.evaluate(cell);
        if (cellValue == null) {
            value = "Blank";
        } else {

            try {
                switch (cellValue.getCellType()) {
                    case HSSFCell.CELL_TYPE_BOOLEAN://布尔类型
                        value = "" + cellValue.getBooleanValue();
                        break;
                    case HSSFCell.CELL_TYPE_NUMERIC://数值类型
                        // 返回数值类型的值
                        Object inputValue = null;// 单元格值
                        Long longVal = Math.round(cellValue.getNumberValue());
                        Double doubleVal = cellValue.getNumberValue();
                        if (Double.parseDouble(longVal + ".0") == doubleVal) {   //判断是否含有小数位.0
                            inputValue = longVal;
                        } else {
                            inputValue = doubleVal;
                        }
                        DecimalFormat df = null;    //格式化为四位小数，按自己需求选择；
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                            df = new DecimalFormat("#.####");
                        }
                        value = String.valueOf(df.format(inputValue));
                        break;
                    case HSSFCell.CELL_TYPE_STRING://字符串
                        value = "" + cellValue.getStringValue();
                        break;
                    case HSSFCell.CELL_TYPE_BLANK://单元格为空
                        value = "bank";
                        break;
                    case HSSFCell.CELL_TYPE_ERROR:
                        value = "非法字符！";
                        break;
                    case HSSFCell.CELL_TYPE_FORMULA://公式形
                        value = cell.getCellFormula() + "";
                        break;
                    default:
                        value = "未知类型";
                        break;
                }

            } catch (Exception e) {
//                Apledialog("类型出错", e.toString() + "请检查文档格式，如有疑问，返回首页详情页面！！", false);
                cuowuToast("类型出错请检查文档格式，如有疑问，返回首页详情页面！！" + e.toString()); panduan=0;
            }
        }
        return value;
    }

    /**
     *
     * @param Tost
     */
    public void cuowuToast(final String Tost) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ToFile_duanxinactivity.this, Tost, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK)
        {
            Uri uri = data.getData();
            if ("file".equalsIgnoreCase(uri.getScheme()))
            {//使用第三方应用打开
                path = uri.getPath();//文件地址
                AlepDilog(path);
            }
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)
            {//4.4以后
                path = getPath(this, uri);
                AlepDilog(path);
            } else
            {//4.4以下下系统调用方法
                path = getRealPathFromURI(uri);
                AlepDilog(path);
            }
        }


    }

    public  void AlepDilog(String path){
        AlertDialog.Builder normalMoreButtonDialog = new AlertDialog.Builder(ToFile_duanxinactivity.this);
        normalMoreButtonDialog.setTitle("数据解析");
        normalMoreButtonDialog.setMessage("确定解析\t"+getFileName(path)+"\t此文件吗?");
        //设置按钮
        normalMoreButtonDialog.setPositiveButton("确定"
                , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                        dialog.dismiss();
                        showSpinner();


                    }
                });

        normalMoreButtonDialog.setNeutralButton("取消"
                , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        normalMoreButtonDialog.create().show();
    }
    /**
     * //4.4以下下系统调用方法
     */
    public String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
            cursor.close();
        }
        return res;
    }

    /**
     * @param context
     * @param uri
     * @return
     */
    @SuppressLint("NewApi")
    public String getPath(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }


    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * 进度
     *
     * @param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            Message message = mHandler.obtainMessage(EVENT_TIME_TO_CHANGE_IMAGE);
            mHandler.sendMessage(message);
        }

    }

    /**
     * 上一个Activity打开当前Activity的信息传递
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case EVENT_TIME_TO_CHANGE_IMAGE:
                    if (data == 1) {
                        MsgMobanActivity.closeProgressDialog();
                    } else {
                        shouyeFragment.closeProgressDialog();
                    }

                    break;
            }
        }
    };

    /**
     * s搜索本地Excel
     *
     * @param fileType
     * @return
     */
    public void getFilesByType(int fileType) {
        List<FileBean> files1 = new ArrayList<FileBean>();

//        Cursor c = null;
//
//        c = getContentResolver().query(MediaStore.Files.getContentUri("external"), new String[]{"_id", "_data", "_size"}, null, null, null);
//        int dataindex = c.getColumnIndex(MediaStore.Files.FileColumns.DATA);
//        int sizeindex = c.getColumnIndex(MediaStore.Files.FileColumns.SIZE);
//
//        while (c.moveToNext()) {
//            path = c.getString(dataindex);
//            if (FileUtils.getFileType(path) == fileType) {
//                if (!FileUtils.isExists(path)) {
//                    continue;
//                }
//                long size = c.getLong(sizeindex);
//
//                FileBean fileBean = new FileBean(path.replace("/storage/emulated/0/", ""), FileUtils.getFileIconByPath(path), size);
//                files.add(fileBean);
//            }
//        }
        executorService= Executors.newFixedThreadPool(100);
        int size=0;
        if (biaoji==1) {
            String path = Environment.getExternalStorageDirectory().getPath();
            File file1 = new File(path);
            final File[] files = file1.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    if (!(file.getPath().equals(path+"/DICM")||file.getPath().equals(path+"/alipay")||file.getPath().equals(path+"/Android"))) {
                        listDir1.add(file);
                    }
                }
                if (file.getName().endsWith(".xls") || file.getName().endsWith(".xlsx")) {
                    fileBeans.add(new FileBean(file.getPath(), R.drawable.file_excel, file.length()));
                }
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                tishi();
            }
            size=listDir1.size();
        }else if (biaoji==2){
            size=listDir2.size();
        }else if (biaoji==3){
            size=listDir3.size();
        }
        for (int i=0;i<size;i++) {
            final int finalI = i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    String path="";
                    if (biaoji==3){
                        path = listDir3.get(finalI).toString();
                    }else if (biaoji==2){
                        path = listDir2.get(finalI).toString();
                    }else if (biaoji==1){
                        path = listDir1.get(finalI).toString();
                    }
                    File file = new File(path);
                    File[] files1 = file.listFiles();
                    bianli(files1, finalI);
                }
            };
            executorService.execute(runnable);
        }
        executorService.shutdown();
        shuaxin();

    }
    private void bianli(File[] files,int i) {
        for(File file:files){
            if (file.isDirectory()){
                if (biaoji==3){
                    bianli(file.listFiles(),2);
                }else if (biaoji==2){
                    synchronized(this) {
                        listDir3.add(file.getPath());
                    }
                }else if (biaoji==1){
                    synchronized(this) {
                        listDir2.add(file.getPath());
                    }
                }
            }else if (file.getName().endsWith(".xls")||file.getName().endsWith(".xlsx")){
                synchronized(this) {
                    fileBeans.add(new FileBean(file.getPath(), R.drawable.file_excel, file.length()));
                }
            }
        }
    }
    int bbbb=0;
    public void shuaxin() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (executorService.isTerminated()) {
                        Log.e("------------>", "==============");
                        if (biaoji == 1) {
                            handler2.sendEmptyMessage(1);
                            break;
                        } else if (biaoji==2){
                            handler2.sendEmptyMessage(2);
                            break;
                        } else {
                            handler2.sendEmptyMessage(0);
                            break;
                        }
                    }
                    Log.e("------------>", String.valueOf(bbbb += 1));
                }
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    Handler handler2=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    mAdapter = new AnimalAdapter(fileBeans, mContext);
                    list_animal.setAdapter(mAdapter);
                    progressDialog.dismiss();
                    biaoji=1;
                    break;
                case 1:
                    biaoji=2;
                    listDir1.clear();
                    getFilesByType(1);
                    break;
                case 2:
                    biaoji=3;
                    listDir2.clear();
                    getFilesByType(1);
                    break;
            }
        }
    };
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void tishi(){
        progressDialog=new ProgressDialog(this);
        progressDialog.setTitle("提示！");
        progressDialog.setMessage("请稍后……正在扫描文件");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.create();
        progressDialog.show();
    }


    @Override
    public boolean onQueryTextSubmit(String query) {
        if (id_file_search1s != null) {
            // 得到输入管理对象
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                // 这将让键盘在所有的情况下都被隐藏
                imm.hideSoftInputFromWindow(id_file_search1s.getWindowToken(), 0); // 输入法如果是显示状态，那么就隐藏输入法
            }
            id_file_search1s.clearFocus(); // 不获取焦点
        }

        return true;

    }

    @Override
    public boolean onQueryTextChange(String s) {
        if (s == null || s.length() == 0) {
            list_animal.clearTextFilter();
            mAdapter.getFileter().filter("");
        } else {
            mAdapter.getFileter().filter(s);
        }
        return true;
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}